/*
 * Progetto, a new java application 
 *
 * Copyright (c) 2010, Red Hat Inc. or third-party contributors as
 * indicated by the @author tags or express copyright attribution
 * statements applied by the authors.  All third-party contributions are
 * distributed under license by Red Hat Inc.
 *
 * This copyrighted material is made available to anyone wishing to use, modify,
 * copy, or redistribute it subject to the terms and conditions of the GNU
 * Lesser General Public License, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
 * for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this distribution; if not, write to:
 * Free Software Foundation, Inc.
 * 51 Rattazzi Street, Fifth Floor
 * Pomezia, RM  00040  Italy
 */
package com.jfootball.business.impl;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.directwebremoting.annotations.RemoteProxy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jfootball.dao.UserDao;
import com.jfootball.domain.user.RoleBean;
import com.jfootball.domain.user.UserBean;
import com.jfootball.domain.user.UserLogged;
import com.jfootball.service.UserService;

@Transactional(readOnly = true)
@Service("userService")
@RemoteProxy(name = "userService")
public class UserServiceImpl implements UserDetailsService, UserService
{

	protected Logger log = Logger.getLogger(this.getClass());

	private final UserDao userDao;

	@Autowired
	public UserServiceImpl(UserDao userDao) 
	{
		this.userDao = userDao;
	}

	@Transactional(readOnly = false)
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException 
	{
		log.info("--------------------- User Login --------------------- ");

		UserBean user = userDao.findUserByName(username);
		
		if (user != null) {
			// convert roles
			List<GrantedAuthority> roles = obtainGrantedAuthority(user);
			
			// save user logged
			UserLogged userLogged = new UserLogged();
			userLogged.setUserId(user.getId());
			userLogged.setTimeLogged(new Timestamp(System.currentTimeMillis()));
			
			userDao.saveOrUpdateUserLogged(userLogged);

			// initialize user
			log.info("User '" + user.getUsername() + "' logged!");

			return makeSecurityUser(user, roles);
		} else {			
			log.error("No user with username '" + username + "' found!");
			throw new UsernameNotFoundException("No user with username '" + username + "' found!");
		}
	}

	private List<GrantedAuthority> obtainGrantedAuthority(UserBean user) 
	{
		List<GrantedAuthority> roles = new ArrayList<GrantedAuthority>();
		for (RoleBean r : user.getRoles()) {
			roles.add(new SimpleGrantedAuthority(r.getName()));
		}
		return roles;
	}

	private UserDetails makeSecurityUser(UserBean user, List<GrantedAuthority> roles) 
	{
		UserDetails userDetails = new MyUserDetails(user, roles);

		return userDetails;
	}
	
	public static class MyUserDetails implements UserDetails {
	    private UserBean user;
	    private List<GrantedAuthority> roles;

	    public MyUserDetails(UserBean user, List<GrantedAuthority> roles) {
	      this.user = user;
	      this.roles = roles;
	    }

	    public List<GrantedAuthority> getAuthorities() {
	      return roles;
	    }

	    public String getPassword() {
	      return user.getPassword();
	    }

	    public String getUsername() {
	      return user.getUsername();
	    }
	    
	    public UserBean getUser() {
			return user;
		}

		public void setUser(UserBean user) {
			this.user = user;
		}

		public boolean isEnabled() {
	    	return true;
	    }
	    
	    public boolean isAccountNonLocked() {
	    	return true;
	    }
	    
	    public boolean isAccountNonExpired() {
	    	return true;
	    }
	    
	    public boolean isCredentialsNonExpired() {
	    	return true;
	    }

	  }
	
	/**
	 * @param idTeam
	 * @return
	 */
	public UserBean getEntityByID(Long idUser)
	{
		return userDao.getUserByID(idUser);
	}

	/**
	 * @param name
	 * @return
	 */
	public UserBean getEntityByDesc(String name)
	{
		return userDao.getUserByName(name);
	}	

	/**
	 * @param nationId
	 * @param divisionId
	 * @return
	 */
	public List<UserBean> getUsers() 
	{
		return userDao.listUsers();
	}

	/**
	 * Method to save team
	 * 
	 * @param team - the team to save
	 */
	public void saveUser(UserBean obj)
	{
		userDao.saveOrUpdateUser(obj);
	}	

	/**
	 * @param idTeam
	 */
	public void deleteUser(Long idUser)
	{
		userDao.deleteUser(idUser);
	}	

}